/**
 * Copyright (C), 2017-2018, XXX有限公司
 * FileName: NioBlockClient
 * Author:   zengjian
 * Date:     2018/9/17 19:01
 * Description:
 * History:
 * <author>          <time>          <version>          <desc>
 * 作者姓名           修改时间           版本号              描述
 */
package fun.codedesign.jdk.socket.nio.block;


import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.Scanner;

/**
 * 〈〉<br>
 * 〈一句话描述〉
 *
 * @author zengjian
 * @create 2018/9/17 19:01
 */
public class NioBlockClient {

    private SocketChannel socketChannel;

    public NioBlockClient() {
        try {
            socketChannel = SocketChannel.open(new InetSocketAddress("localhost", 8080));
            socketChannel.configureBlocking(true); // 如果为true就不能注册到多路复用器上
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public String sendMessage(String message) throws IOException {
        ByteBuffer byteBuffer = ByteBuffer.allocate(message.getBytes().length);
        byteBuffer.put(message.getBytes("utf-8"));
        byteBuffer.flip();
        socketChannel.write(byteBuffer);

        ByteBuffer readbuffer = ByteBuffer.allocate(1000);
        socketChannel.read(readbuffer);
        readbuffer.flip();
        byte[] readBytes = new byte[readbuffer.remaining()];
        readbuffer.get(readBytes);
        return new String(readBytes);
    }

    public static void main(String[] args) throws IOException {
        NioBlockClient client = new NioBlockClient();
        try(Scanner scanner = new Scanner(System.in)){
            for (int i = 0; i < 100; i++) {
                String resp = client.sendMessage("123");
                System.out.println("返回结果:" + resp);
            }
        }
    }
}